package cn.zwx.learn.basic.groovy.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.zwx.learn.basic.groovy.GroovyService;
import cn.zwx.learn.basic.groovy.LoadGroovyService;
import cn.zwx.learn.basic.groovy.handler.GroovyHandler;
import com.sun.jndi.ldap.pool.PooledConnectionFactory;
import groovy.lang.GroovyClassLoader;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.context.support.GenericGroovyApplicationContext;
import org.springframework.scripting.support.ScriptFactoryPostProcessor;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

import static cn.zwx.learn.basic.groovy.impl.GroovyServiceImpl.groovyCache;
import static cn.zwx.learn.basic.groovy.utils.GroovyUtil.groovyRegister;

/**
 * @description:
 * @projectName:java-basic
 * @see:groovy.impl
 * @author:zhangwenxue
 * @createTime:2021/4/13 19:59
 * @version:1.0
 */
@Service
public class LoadGroovyServiceImpl implements LoadGroovyService, ApplicationContextAware, BeanFactoryAware {

    private Logger logger = LoggerFactory.getLogger(LoadGroovyServiceImpl.class);


    @Autowired
    private GroovyService groovyService;

    public  ApplicationContext applicationContext;

    public DefaultListableBeanFactory beanFactory;


    /**
     * 加载groovy脚本进容器
     * @throws Exception
     */
    @Override
    public void load() throws Exception {
        // 加载groovy脚本
        groovyService.loadClsGroovy();
//        if (CollectionUtil.isEmpty(groovyCache)){
//            return;
//        }
//        String[] arr = new String[1024];
        Set<Map.Entry> set = groovyCache.entrySet();
       // int index = 0;
        for (Map.Entry entry : set) {
            GroovyHandler groovyHandler = groovyRegister.get(entry.getKey().toString());
            String beanName = groovyHandler.getClass().getName();
            // arr[index++] = "action//test//"+ entry.getKey().toString()+".groovy";
            BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(groovyHandler.getClass());
            BeanDefinition beanDefinition = beanDefinitionBuilder.getRawBeanDefinition();
            applicationContext.getAutowireCapableBeanFactory().applyBeanPostProcessorsAfterInitialization(beanDefinition, beanName);
            beanFactory.setAllowBeanDefinitionOverriding(Boolean.TRUE);
            beanFactory.registerBeanDefinition(beanName,beanDefinition);

        }
//      //  GroovyApplicationContext = new GenericGroovyApplicationContext(arr);
//

    }

    @Override
    public void refreshSpringContentDueToGroovy(String beanName) throws Exception {
        if (Optional.ofNullable(this.applicationContext).isPresent()) {
            // 更新文件
            groovyService.loadClsGroovy(beanName);
            // 刷新ioc里面bean
            GroovyHandler groovyHandler = groovyRegister.get(beanName.substring(beanName.lastIndexOf(".")+ 1));
            groovyHandler.invoke(new Object());
            BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(groovyHandler.getClass());
            BeanDefinition beanDefinition = beanDefinitionBuilder.getRawBeanDefinition();
            applicationContext.getAutowireCapableBeanFactory().applyBeanPostProcessorsAfterInitialization(beanDefinition, beanName);
            beanFactory.setAllowBeanDefinitionOverriding(Boolean.TRUE);
            beanFactory.registerBeanDefinition(beanName,beanDefinition);
        }
    }



    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 把groovy脚本交给spring管理
        this.applicationContext = applicationContext;
    }





    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = (DefaultListableBeanFactory)beanFactory;
    }


}
